package com.lekang.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lekang.common.core.domain.entity.SysUser;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.domain.AccraditationRecord;
import com.lekang.domain.PendingTasks;
import com.lekang.service.IAccraditationRecordService;
import com.lekang.service.IPendingTasksService;
import com.lekang.system.mapper.SysUserMapper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.mapper.LeaveRequestMapper;
import com.lekang.domain.LeaveRequest;
import com.lekang.service.ILeaveRequestService;

/**
 * 请假Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-14
 */
@Service
public class LeaveRequestServiceImpl implements ILeaveRequestService 
{
    @Autowired
    private LeaveRequestMapper leaveRequestMapper;


    /**
     * 查询请假
     * 
     * @param id 请假主键
     * @return 请假
     */
    @Override
    public LeaveRequest selectLeaveRequestById(Long id)
    {
        return leaveRequestMapper.selectLeaveRequestById(id);
    }

    /**
     * 查询请假列表
     * 
     * @param leaveRequest 请假
     * @return 请假
     */
    @Override
    public List<LeaveRequest> selectLeaveRequestList(LeaveRequest leaveRequest)
    {
        return leaveRequestMapper.selectLeaveRequestList(leaveRequest);
    }
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private IAccraditationRecordService accraditationRecordService;
    @Autowired
    private IPendingTasksService pendingTasksService;
    @Autowired
    private com.lekang.mapper.ElderlyMapper elderlyMapper;
    @Autowired
    private com.lekang.service.IBedService bedService;

    /**
     * 新增请假
     * 
     * @param leaveRequest 请假
     * @return 结果
     */
    @Override
    public int insertLeaveRequest(LeaveRequest leaveRequest)
    {
//        校验

//        保存请假信息
        leaveRequest.setCreateTime(DateUtils.getNowDate());
        Long userId = SecurityUtils.getUserId();
        leaveRequest.setCreator(userId);
        int num= leaveRequestMapper.insertLeaveRequest(leaveRequest);

        Long newLeaveRequestId=0L;
        if (num > 0) {
            newLeaveRequestId = leaveRequest.getId();
        }

//        设置节点办理人
        Map map=new HashMap();
        map.put("assignee1",userId);
//        根据当前用户的部门查询所属部门中的护理长信息
        SysUser currentUser=sysUserMapper.selectUserById(userId);
        Long deptId= currentUser.getDeptId();//获取当前用户的部门ID
        SysUser nurseLeader=sysUserMapper.selectNurseLeaderByDeptId(deptId);//根据部门ID查询护理长信息
        Long nurseLeaderId=nurseLeader.getUserId();//获取护理长的用户ID
        if(nurseLeaderId==null){
            throw new RuntimeException("未找到该部门的护理长信息");
        }
        map.put("assignee2",nurseLeaderId);//设置护理长为节点2的办理人



//          4实例创建
        runtimeService.startProcessInstanceByKey("qingjia",leaveRequest.getId().toString(),map);
//          完成节点
        Task task = taskService.createTaskQuery()
                .processInstanceBusinessKey(leaveRequest.getId().toString())
                .processDefinitionKey("qingjia")
                .taskAssignee(userId.toString()).singleResult();
        if(task!=null){
            taskService.complete(task.getId());
        }
//        6保存审批记录
        AccraditationRecord record=new AccraditationRecord();
        record.setOpinion("同意");
        record.setType("请假");
        record.setFinishTime(new Date());
        record.setApproverId(nurseLeaderId);
        record.setApproverName(SecurityUtils.getUsername());
        record.setApproverNameRole(sysUserMapper.selectApproverNameRole(userId));   //申请人角色
        record.setNextApproverId(nurseLeaderId);
        record.setNextApproverRole(sysUserMapper.selectNextApproverNameRole(nurseLeaderId));
        record.setNextApprover(sysUserMapper.selectNurseLeaderName(nurseLeaderId));
        record.setBussniessId(leaveRequest.getId().toString());
        record.setCurrentStep("申请请假");
        record.setNextStep("申请审批");
        record.setAuditStatus("通过");
        record.setStepNo(2L);
        record.setHandleType("申请中");
        record.setLeaveContentId(newLeaveRequestId);
        accraditationRecordService.insertAccraditationRecord(record);
//      7保存我的申请
        PendingTasks pendingTasks=new PendingTasks();
        pendingTasks.setBussniessId(leaveRequest.getId());
        pendingTasks.setTaskId(task.getId());
        pendingTasks.setTitle(leaveRequest.getElderlyName()+"的请假申请");
        pendingTasks.setType(2L);
        pendingTasks.setAssignee(SecurityUtils.getUsername());
        pendingTasks.setAssigneeId(userId);
        pendingTasks.setStatus(1l);
        pendingTasks.setApplicationTime(leaveRequest.getCreateTime());
        pendingTasks.setApplicat(SecurityUtils.getUsername());
        pendingTasks.setApplicatId(userId);
        pendingTasks.setFinishTime(new Date());
        pendingTasks.setIsHandle(1l);
        pendingTasks.setStepNo(2L);  //1已经完整，下次进入2
        pendingTasksService.insertPendingTasks(pendingTasks);
//        8保存我的代办任务--下一个人的待办任务
//        查询工作流下一个任务节点id
        Task nextTask = taskService.createTaskQuery()
                .processInstanceBusinessKey(leaveRequest.getId().toString())
                .processDefinitionKey("qingjia")
                .taskAssignee(nurseLeaderId.toString()).singleResult();
        PendingTasks pt=new PendingTasks();
        pt.setBussniessId(leaveRequest.getId());
        pt.setTaskId(nextTask.getId());
        pt.setTitle(leaveRequest.getElderlyName()+"的请假申请");
        pt.setType(2L);
        pt.setAssignee(record.getNextApprover());
        pt.setAssigneeId(record.getNextApproverId());
        pt.setStatus(1L);
        pt.setBussniessId(leaveRequest.getId());
        pt.setApplicationTime(leaveRequest.getCreateTime());
        pt.setApplicat(SecurityUtils.getUsername());
        pt.setApplicatId(userId);
        pt.setIsHandle(0L);
        pt.setStepNo(2L);
        pendingTasksService.insertPendingTasks(pt);

        return num;
    }

    /**
     * 修改请假
     * 
     * @param leaveRequest 请假
     * @return 结果
     */
    @Override
    public int updateLeaveRequest(LeaveRequest leaveRequest)
    {
        // 更新请假记录
        int result = leaveRequestMapper.updateLeaveRequest(leaveRequest);
        
        // 如果更新成功，根据请假状态联动更新床位状态
        if (result > 0 && leaveRequest.getId() != null) {
            try {
                // 查询请假记录获取老人ID
                LeaveRequest dbLeaveRequest = leaveRequestMapper.selectLeaveRequestById(leaveRequest.getId());
                if (dbLeaveRequest != null && dbLeaveRequest.getElderlyId() != null) {
                    // 根据老人ID查询床位ID
                    com.lekang.domain.Elderly elderly = elderlyMapper.selectElderlyById(dbLeaveRequest.getElderlyId());
                    if (elderly != null && elderly.getBedId() != null) {
                        Long bedId = elderly.getBedId();
                        
                        // 根据请假状态更新床位状态
                        String leaveStatus = leaveRequest.getLeaveStatus();
                        String pizhun = leaveRequest.getPizhun();
                        
                        // 情况1：审批通过，请假状态为"已批准"或pizhun为"请假中"，床位状态改为"请假中"
                        if ("已批准".equals(leaveStatus) || "请假中".equals(pizhun)) {
                            bedService.askForLeave(bedId);
                        }
                        // 情况2：销假，pizhun为"已返回"，床位状态改为"已入住"
                        else if ("已返回".equals(pizhun)) {
                            bedService.cancelLeave(bedId);
                        }
                    }
                }
            } catch (Exception e) {
                // 记录日志，但不影响请假记录的更新
                System.err.println("更新床位状态失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        return result;
    }

    /**
     * 批量删除请假
     * 
     * @param ids 需要删除的请假主键
     * @return 结果
     */
    @Override
    public int deleteLeaveRequestByIds(Long[] ids)
    {
        return leaveRequestMapper.deleteLeaveRequestByIds(ids);
    }

    /**
     * 删除请假信息
     * 
     * @param id 请假主键
     * @return 结果
     */
    @Override
    public int deleteLeaveRequestById(Long id)
    {
        return leaveRequestMapper.deleteLeaveRequestById(id);
    }

    @Override
    public PageInfo<LeaveRequest> selectLeaveRequestPage(LeaveRequest leaveRequest, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<LeaveRequest> leaveRequests = leaveRequestMapper.selectLeaveRequestPage(leaveRequest);
        PageInfo<LeaveRequest> pageInfo=new PageInfo<>(leaveRequests);
        return pageInfo;
    }

    @Override
    public List<LeaveRequest> selectByElderlyId(Long elderlyId) {
        return leaveRequestMapper.selectByElderlyId(elderlyId);
    }

    /**
     * 查询请假列表
     *
     * @param leaveRequest 请假
     * @return 请假
     */
    @Override
    public List<LeaveRequest> selectLeaveRequestList1(LeaveRequest leaveRequest)
    {
        return leaveRequestMapper.selectLeaveRequestList(leaveRequest);
    }

}
